package com.ftg.learn.springbootmq.topic.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 用户消息消费者
 */
@Component
public class UserConsumer {

    /**
     * 监听用户队列消息
     *
     * @param message 消息内容
     * @param channel 通道
     * @param tag     消息标签
     * @throws IOException IO异常
     */
    @RabbitListener(queues = "user.queue")
    public void handleUserMessage(Map<String, Object> message, Channel channel,
                                  @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            System.out.println("用户消费者接收到消息: " + message);
            // 处理用户相关业务逻辑
            processUserMessage(message);

            // 手动确认消息
            channel.basicAck(tag, false);
        } catch (Exception e) {
            // 拒绝消息并重新入队
            channel.basicNack(tag, false, true);
            e.printStackTrace();
        }
    }

    /**
     * 处理用户消息
     *
     * @param message 消息内容
     */
    private void processUserMessage(Map<String, Object> message) {
        String action = (String) message.get("action");
        Object data = message.get("data");

        switch (action) {
            case "register":
                System.out.println("处理用户注册: " + data);
                break;
            case "login":
                System.out.println("处理用户登录: " + data);
                break;
            case "update":
                System.out.println("处理用户信息更新: " + data);
                break;
            default:
                System.out.println("未知用户操作: " + action);
        }
    }
}

